package dstation.controller;


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import dstation.databeans.GraphResultBean;
import dstation.databeans.ResultBean;
import dstation.databeans.Reading;
import dstation.databeans.WidgetTag;
import dstation.model.ResultDAO;
import dstation.model.RobotDAO;
import dstation.model.SensorDAO;
import dstation.model.TestDAO;

/**
 * Servlet implementation class DStation
 */
public class DStationServlet extends HttpServlet {

	
	private ResultDAO resultDAO;
	private String scriptBegin;
	private String scriptEnd;

	/* (non-Javadoc)
	 * @see javax.servlet.GenericServlet#init()
	 */
	@Override
	public void init() throws ServletException {
		super.init();
		new File("webapps/DiagStationWebApp/amlinedata/").mkdirs();
		RobotDAO robotDAO = new RobotDAO("robot");
		SensorDAO sensorDAO = new SensorDAO("sensor");
		TestDAO testDAO = new TestDAO("test");
		resultDAO = new ResultDAO("result", "robot", "test", "sensor");
		scriptBegin = "<script type=\"text/javascript\">\n" +
				"\t// <![CDATA[	\n" +
				"\tvar so = new SWFObject(\"./amline/amline.swf\", \"amline\", \"100%\", \"100%\", \"8\", \"#FFFFFF\");\n" +
				"\tso.addVariable(\"path\", \"./amline/\");\n" +
				"\tso.addVariable(\"settings_file\", encodeURIComponent(\"amline_settings.xml\"));\n";
		scriptEnd = "\tso.write(\"flashcontent\");\n" +
				"\t// ]]>\n" +
				"</script>\n";
	}


	private static final long serialVersionUID = 1L;
	private static final String[] COLORS = {"Red","Blue","Green","Orange","Purple"};

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DStationServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		ArrayList<WidgetTag> widgetList = new ArrayList<WidgetTag>();
		widgetList.add(new WidgetTag("menu",""));
		String path = request.getRequestURL().toString();
		List<ResultBean> list = new ArrayList<ResultBean>();
		List<String> cam = new ArrayList<String>();
		if(path.endsWith("viewrobots.do")){
			widgetList.add(new WidgetTag("robotTable",""));
		}
		else if(path.endsWith("viewrobot.do")){
			Integer.parseInt(request.getParameter("id").toString());
			widgetList.add(new WidgetTag("robot",request.getParameter("id").toString()));
		}
		else if(path.endsWith("testcreate.do")){
			widgetList.add(new WidgetTag("testeditcreate",""));
		}
		else if(path.endsWith("viewtests.do")){
			widgetList.add(new WidgetTag("viewtests",""));
		}
		else if(path.endsWith("edittest.do")){
			widgetList.add(new WidgetTag("testeditcreate",request.getParameter("id").toString()));
		}
		else if(path.endsWith("recenttests.do")){
			widgetList.add(new WidgetTag("recenttests",""));
		}
		else if(path.endsWith("search.do")){
			widgetList.add(new WidgetTag("search",""));
		}
		else if(path.endsWith("webcam.do")){
			cam.add("show webcam!");
		}
		else if(path.endsWith("viewresults.do")){
			String[] ids = request.getParameter("results").toString().split(";");
			for(String id:ids){
				try{
					int idnum = Integer.parseInt(id);
					ResultBean r = new ResultBean();
					r.setResultid(idnum);
					r = resultDAO.lookup(r, true);
					list.add(r);
					if(list.size()>=5){break;}
				}catch(NumberFormatException e){
				} catch (SQLException e) {
					throw new ServletException(e);
				} catch (ClassNotFoundException e) {
					throw new ServletException(e);
				}
			}
			if(!list.isEmpty()){
				ArrayList<GraphResultBean> colors = new ArrayList<GraphResultBean>();
				for(ResultBean res : list){
					GraphResultBean e = new GraphResultBean();
					e.setId(res.getResultid()+"");
					colors.add(e);
				}
				for(int i = 0; i<colors.size(); i++){
					colors.get(i).setColor(COLORS[i]);
				}
				String filepath = createXMLDataFile(session.getId(),list);
				String scriptLine = "\tso.addVariable(\"data_file\", encodeURIComponent(\""+ filepath +"\"));\n";
				session.setAttribute("jscrip", scriptBegin + scriptLine + scriptEnd);
				session.setAttribute("testcolors", colors);
			}
		}
		session.setAttribute("arr", list);
		session.setAttribute("widgetList", widgetList);
		session.setAttribute("cam", cam);
		response.sendRedirect("Home.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}


	public static synchronized String createXMLDataFile(String filename, List<ResultBean> list){
		String absName ="webapps/DiagStationWebApp/amlinedata/"+filename+".xml";
		try {
			FileWriter writer = new FileWriter(absName);
			writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<chart>\n" +
			"\t<series>\n");
			int i = 0;
			for(Reading r : list.get(0).getData()){
				writer.write("\t\t<value xid=\""+i+"\">"+ r.realVal +"</value>\n");
				i++;
			}
			writer.write("\t</series>\n");
			writer.write("\t<graphs>\n");
			i=0;
			for(ResultBean b : list){
				writer.write("\t\t<graph gid=\""+i+"\">\n");
				writer.write("\t\t\t<axis>left</axis>\n");                   
				writer.write("\t\t\t<line_width>2</line_width>\n");              
				writer.write("\t\t\t<color>#999999</color>\n");
				writer.write("\t\t\t<bullet>square</bullet>\n"); 
				writer.write("\t\t\t<bullet_size>8</bullet_size>\n");
				writer.write("\t\t\t<selected>true</selected>\n");
				writer.write("\t\t\t<balloon_text>\n");
				writer.write("\t\t\t\t<![CDATA[${value}]]>\n");
				writer.write("\t\t\t</balloon_text>\n");
				int j = 0;
				for(Reading r : b.getData()){
					writer.write("\t\t\t<value xid=\""+j+"\">"+r.robotVal+"</value>\n");
					j++;
				}
				writer.write("\t\t</graph>\n");
				i++;
			}
			writer.write("\t</graphs>\n");
			writer.write("</chart>\n");
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "./amlinedata/"+filename+".xml";
	}
}
